<script setup>
import { computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

import { useDetectionStoreHook } from "../../store/modules/detection";
import { useProcessStoreHook } from "../../store/modules/process";
import { useInfoStoreHook } from "../../store/modules/info";
import useLoading from "../../utils/loading";

import SelectWorkCenter from "./SelectWorkCenter.vue";
import SelectPartModel from "./SelectPartModel.vue";
import ScrollSelect from "../../components/scroll-select/Index.vue";

import config from "../../../../../package.json";

const info = useInfoStoreHook();
const processStore = useProcessStoreHook();
const detection = useDetectionStoreHook();

async function selectProcess(option) {
  const loading = useLoading();
  await processStore.setProcess(option?.id);
  await processStore.getTechnicParams();
  loading.close();
}

onMounted(async () => {
  const loading = useLoading();
  loading.setText("初始化中，请稍后...");
  await processStore.defaultSetup();
  loading.close();
});

async function login() {
  if (info.isLogin) {
    ElMessageBox.confirm("您确认退出登录吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        ElMessage({
          message: `再见，${info.realname}，欢迎下次使用！`,
          type: "success"
        });
        info.userLogout();
      })
      .catch(() => {});
  } else {
    const loading = useLoading();
    const res = await info.userLogin();
    // if (res.code === 0) {
    //   await detection.updateDataset();
    // }
    if (res.code === 1) {
      ElMessage.error(res.msg);
    }
    loading.close();
  }
}

// watch([() => detection.fields, () => processStore.modelCode], async (val) => {
//   if (val[0] && val[1]) {
//     console.log(val[0]);
//     await processStore.getTechnicParams();
//   }
// });

function usernumbEnterKeyDown(e) {
  if (e.keyCode === 13 && !info.isLogin) {
    login();
  }
}

let userChangeFlag = false;
async function workTypeChange(newOpt, oldOpt) {
  if (userChangeFlag) {
    userChangeFlag = false;
    return;
  }
  const doLen = detection.dataset.filter((d) => !d.finish_at).length;
  if (oldOpt?.value >= 10 && oldOpt?.value < 20 && doLen < 20) {
    ElMessageBox.confirm(
      `当前 ${oldOpt.label} 仅记录${doLen}条数据，未做满20件，确定要切换吗？`,
      "警告",
      {
        type: "warning",
        confirmButtonText: "切 换",
        cancelButtonText: "取 消"
      }
    )
      .then(async () => {
        await detection.finishBatch();
        await detection.updateDataset();
      })
      .catch(() => {
        info.work_type = oldOpt.value;
        userChangeFlag = true;
      });
  } else {
    await detection.finishBatch();
    await detection.updateDataset();
  }
}

const identityOptions = computed(() => {
  const res = [{ label: "操作员", value: 0 }];
  if (info.realIdentity >= 1) {
    res.push({ label: "班组长", value: 1 });
    if (info.realIdentity >= 2) {
      res.push({ label: "巡检员", value: 2 });
    }
  }
  return res;
});
</script>

<template>
  <el-form size="large" label-width="80px">
    <el-form-item label="员工信息">
      <el-row class="item-width" :gutter="12">
        <el-col :span="12">
          <el-input
            v-model="info.username"
            :readonly="info.isLogin"
            placeholder="请输入工号或刷卡登录"
            @keydown="usernumbEnterKeyDown"
          />
        </el-col>
        <el-col :span="6">
          <el-button
            class="item-width"
            :type="info.isLogin ? 'primary' : ''"
            :plain="info.isLogin"
            @click="login"
            >{{ info.isLogin ? "退出登录" : "点击登录" }}</el-button
          >
        </el-col>
        <el-col :span="6">
          <scroll-select
            v-model:value="info.identity"
            :options="identityOptions"
            input-style="text-align: center"
          />
          <!-- <el-select v-model="info.identity" placeholder="选择作业身份">
            <el-option :value="0" label="操作员" />
            <el-option v-if="info.realIdentity >= 1" :value="1" label="班组长" />
            <el-option v-if="info.realIdentity >= 2" :value="2" label="巡检员" />
          </el-select> -->
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="岗位信息">
      <el-row :gutter="12" class="item-width">
        <el-col :span="12">
          <select-work-center />
        </el-col>
        <el-col :span="6">
          <scroll-select
            v-model:value="processStore.process"
            :dialog-title="
              !processStore.workCenterId
                ? '请先选择产线'
                : processStore.processes?.length && processStore.processes.length > 0
                ? '点击选择作业岗位'
                : '查无相关岗位'
            "
            :options="processStore.processes"
            input-style="text-align: center"
            :disabled="!(processStore.processes?.length && processStore.processes.length > 0)"
            @selected="selectProcess"
          />
        </el-col>
        <el-col :span="6">
          <scroll-select
            v-model:value="info.work_type"
            dialog-title="选择作业类型"
            :options="info.workTypeOptions"
            input-style="text-align: center"
            @change="workTypeChange"
          />
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="生产型号">
      <select-part-model />
    </el-form-item>
  </el-form>
  <div class="footer">{{ `版本：${config.version}  copyright © 2023 ${config.author}` }}</div>
</template>

<style lang="scss" scoped>
.item-width {
  width: 100%;
}
.select-box {
  margin: 24px 0 0 0;
  .select-space {
    width: 100%;
  }
}
.select-btn {
  width: 100% !important;
  height: 56px !important;
}
:deep(.el-space__item) {
  width: 100%;
}
.owner-dialog-content {
  padding: 10px 15px;
  font-size: 18px;
  line-height: 24px;
  // vertical-align: middle;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}
.btn-group {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  padding-top: 15px;
}
.footer {
  height: 28px;
  line-height: 28px;
  width: 100%;
  box-sizing: border-box;
  padding: 0 38px 0 0;
  font-size: 10px;
  color: #606060;
  position: absolute;
  text-align: right;
  bottom: 4px;
  cursor: default;
  user-select: none;
}
</style>
